package com.itheima.sh.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @作者 itcast
 * @创建日期 2021/5/16 15:41
 **/
//@Component
public class LoginFilter implements GlobalFilter {
    /**
     * @param exchange  交换机 : 包含了 请求对象  和 响应对象
     * @param chain   链 : 通过链来放行请求
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2. 获取请求头中的 access-token信息
        String token = request.getHeaders().getFirst("access-token");
        // 3. 如果token不为空 并且 值为admin
        if(StringUtils.isNotBlank(token) && "admin".equals(token)){
            //   3.1  放行请求
            return chain.filter(exchange);
        }
        // 4. 终止请求，并响应状态设置为401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete(); // 终止请求
    }
}
